package net.byg.task;

import net.byg.util.UploadAssetsUtil;
import net.byg.ftp.ContinueFTP;
import net.byg.model.FtpInfo;
import org.apache.commons.lang.time.StopWatch;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.Objects;

/**
 * 上传静态资源
 */
public class UploadFilesRunTask implements Runnable {
    private static final Logger logger = Logger.getLogger(UploadFilesRunTask.class);

    private FtpInfo ftpInfo;

    public UploadFilesRunTask(FtpInfo ftpInfo) {
        this.ftpInfo = ftpInfo;
    }

    @Override
    public void run() {
        Thread.currentThread().setName(Thread.currentThread().getName() + "(" + ftpInfo.getIp() + ")");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ContinueFTP myFtp = new ContinueFTP();
        if (Objects.toString(ftpInfo.getLocalDir(), "").equals("") || Objects.toString(ftpInfo.getServerDir(), "").equals("")) {
            logger.info(ftpInfo + " 配置错误，已取消该任务");
            return;
        }
        try {
            myFtp.connect(ftpInfo.getIp(), ftpInfo.getPort(), ftpInfo.getUsername(), ftpInfo.getPassword());
            UploadAssetsUtil.upload(myFtp, ftpInfo.getLocalDir(), ftpInfo.getServerDir());
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            try {
                myFtp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info(ftpInfo.getIp() + " 上传完成-" + stopWatch.toString());
        }
    }
}